package com.example.java.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class CustomProducerSync {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建 Kafka 生产者的配置对象
        Properties properties = CustomProducerSync.getKafkaProperties();
        // 创建 kafka 生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
        // 调用 send 方法发送消息
        for (int i = 0; i < 5; i++) {
            // 默认为异步发送
            // kafkaProducer.send(new ProducerRecord<>("kafka_test", "Class: CustomProducerSync_" + i));
            // 加入 get 方法实现同步发送
            kafkaProducer.send(new ProducerRecord<>("producer1", "ni hao, i am producer1, send message " + i)).get();
        }
        // 关闭资源
        kafkaProducer.close();
        System.out.println("CustomProducerSync executed successfully");
    }

    private static Properties getKafkaProperties() {
        Properties properties = new Properties();
        // 给 kafka 配置对象添加配置信息：bootstrap.servers
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        // key, value 序列化（必须）：key.serializer，value.serializer
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return properties;
    }
}